import {Card,Row,Col,Input,Button,Table,Pagination,Tag,Popconfirm,message }from "antd"
import type { TableProps,PaginationProps,PopconfirmProps  } from 'antd'
import React,{ useState, useEffect, useMemo,useCallback } from "react";
import type {DataType} from './interface'
import {getUserList,deleteUser,batchDeleteUser} from '@/api/userlist'

// 弹框
import UserForm from './useForm'
import { useDispatch } from "react-redux";
import { setUserData } from '@/store/user/userSlice'
interface searchType{
    companyName: string;
    contact: string;
    phone:string;
}
function Users() {
    const [dataList, setDataList] = useState<DataType[]>([])
    const [page,setPage]=useState<number>(1)
    const [pageSize,setPageSize]=useState<number>(10)
    const [total,setToal]=useState<number>(0)
    const [loading,setLoading]=useState<boolean>(false)
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
    const [title,setTitle] = useState<string>('')
    // const [disabled,setDisabled]=useState<boolean>(true)
    const dispatch = useDispatch()
    const [isModalOpen, setIsModalOpen] = useState(false);

    const [formData,setFormData]=useState<searchType>({
        companyName: '',
        contact: '',
        phone:'',
    })
    const loadData= async ()=>{
        setLoading(true)
        const {data:{list,total}} = await getUserList({...formData,page,pageSize})
        // console.log('res',list,total)
        setDataList(list)
        setToal(total)
        setLoading(false)

    }
    const handleChange = (e: React.ChangeEvent<HTMLInputElement>)=>{
        const { name, value }= e.target
        setFormData(prevState=>({
            ...prevState,
            [name]: value
        }))
    }

    useEffect(()=>{
        loadData()
    },[page,pageSize])

    const onSelectChange = (selectedRowKeys: React.Key[],selectedRows:any)=>{
        setSelectedRowKeys(selectedRowKeys)
    }
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange
    }

    const onChange:PaginationProps['onChange'] =(page,pageSize)=>{
        console.log(page,pageSize)
        setPage(page)
        setPageSize(pageSize)
        loadData()
    }
    // 重置
    const resetData = ()=>{ 
        setSelectedRowKeys([])
        setFormData({ companyName:'',contact:'',phone:''})
        setPage(1)
        setPageSize(10)
        loadData()
    }
    // 确认删除
    const confirm = async (id:string) => {
        console.log(id);
        const res = await deleteUser(id)
        console.log('res',id,res)
        message.success('删除成功');
        loadData()
    };
    const cancel: PopconfirmProps['onCancel'] = (e) => {
        console.log(e);
        message.error('Click on No');
    };
    const disabled=useMemo(()=>{
        return selectedRowKeys.length? false : true
    },[selectedRowKeys])
    // 新增
    const add = ()=>{
        setIsModalOpen(true)
        setTitle('新增')
        dispatch(setUserData({}))

    }
    // 编辑
    const edit = (val:DataType)=>{
        setIsModalOpen(true)
        setTitle('编辑')
        dispatch(setUserData(val))
    }
    const hideModal = useCallback(()=>{
        setIsModalOpen(false)
    },[])
    // 批量删除
    const batchDelete = async ()=>{
        const res = await batchDeleteUser(selectedRowKeys)
        console.log('res',res)
        message.success('批量删除成功');
        loadData()

    }
    const columns:TableProps<DataType>['columns']  = [
        {
            title: 'No',
            key: 'index',
            fixed: 'left',
            width:60,
            render(value,record,index){
                return index+1
            },
        },
        {
            title: '客户名称',
            dataIndex: 'name',
            key: 'name',
            width:120,
    
        },
        {
            title: '经营状态',
            dataIndex: 'status',
            key: 'status',
            width:100,
        render(value){
            if(value === 1){
                return <Tag color="green">营业中</Tag>
            }else if(value === 2){
                return <Tag color="#f50">暂停营业</Tag>
            }else if(value === 3){
                return <Tag color="red">已关闭</Tag>
            }
        }
        },
        {
            title: '联系电话',
            dataIndex: 'tel',
            key: 'tel',
        },
        {
            title: '所属行业',
            dataIndex: 'business',
            key: 'business',
            minWidth:120,
        },
        {
            title: '邮箱',
            dataIndex: 'email',
            key: 'email',
            minWidth:160,
        },
        {
            title: '统一信用代码',
            dataIndex: 'creditCode',
            key: 'creditCode',
            minWidth:170,
        },
        {
            title: '工商注册号',
            dataIndex: 'industryNum',
            key: 'industryNum',
            minWidth:140,
        },
        {
            title: '组织机构代码',
            dataIndex: 'organizationCode',
            key: 'organizationCode',
            minWidth:140,
        },
        {
            title: '法人名',
            dataIndex: 'legalPerson',
            key: 'legalPerson',
            width:'100px',
        },
        {
            title: '操作',
            dataIndex: 'operate',
            key: 'operate',
            fixed: 'right',
            minWidth:150,
        render(value,record,index){
            return <>
                <Button type="primary" size="small" onClick={()=>edit(record)}>编辑</Button>
                <Popconfirm
                    title="确定要删除吗"
                    description="确定要删除吗?"
                    onConfirm={()=>confirm(record.id)}
                    onCancel={cancel}
                    okText="是"
                    cancelText="否"
                    >
                    <Button type="primary" size="small" danger className="ml">删除</Button>
                </Popconfirm>
            </>
        }
        },
    ];
    return <div className="mainContent">

        <MyUserForm visible={isModalOpen} hideModal={hideModal} title={title} loadData={loadData} />
        <Card className="search">
            <Row gutter={8}>
                <Col span={6} >
                    <p>企业名称:</p>
                    <Input name="companyName" value={formData.companyName} onChange={handleChange} />
                </Col>
                <Col span={5}>
                    <p>联系人:</p>
                    <Input name="contact" value={formData.contact} onChange={handleChange} />
                </Col>
                <Col span={6}>
                    <p>联系电话:</p>
                    <Input name="phone" value={formData.phone} onChange={handleChange} />
                </Col>
                <Col span={7}>
                    <Button type="primary" onClick={loadData}>查询</Button>
                    <Button className="ml" onClick={resetData}>重置</Button>
                    <Button type="primary" className="ml" onClick={add}>新增企业</Button>
                    <Button danger type="primary" className="ml" disabled={disabled} onClick={batchDelete}>批量删除</Button>
                </Col>
            </Row>
        </Card>
        <Card className="mt tr">
        {/* 表格 */}
        <Table 
            dataSource={dataList} 
            columns={columns} 
            rowKey={(record)=>record.id}
            rowSelection={rowSelection}
            scroll={{ x: 1600, y: 400 }}
            pagination={false}
            loading={loading} />;
        {/* 分页  current={page} pageSize={pageSize}是为了让界面更新*/}
        <Pagination
        className="fr mt"
            total={total}
            current={page}
            pageSize={pageSize}
            showSizeChanger
            showQuickJumper
            showTotal={(total) => `共 ${total} 条`}
            onChange={onChange}
        />
        </Card>
    </div>
}
// 用到 UserForm组件属性的时候才会触发
const MyUserForm = React.memo(UserForm)
export default Users